<template >
  <Dialog class="order-send-card-key-form-dialog" v-model="dialogVisible" title="填写卡密" width="800px">
    <el-descriptions title="订单信息">
      <el-descriptions-item label="商品名称: ">{{skuInfo.spuName}}</el-descriptions-item>
      <el-descriptions-item label="商品面值: ">{{ skuInfo.denomination }}</el-descriptions-item>
      <el-descriptions-item label="数量: ">{{ skuInfo.count }}</el-descriptions-item>
      <el-descriptions-item label="商品单价: ">{{ skuInfo.itemNominalValue/100}} {{ skuInfo.currencyCode}}</el-descriptions-item>
      <el-descriptions-item label="实付金额: " v-if="orderInfo">{{ orderInfo.paymentPrice / 100 }} {{ orderInfo.paymentCurrency}}</el-descriptions-item>
      <el-descriptions-item label="发货方式: ">
        <el-tag v-if="skuInfo.deliveryMethod === EnumDeliveryMethodType.AUTOMATIC">自动</el-tag>
        <el-tag v-if="skuInfo.deliveryMethod === EnumDeliveryMethodType.MANUAL">手动</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="接受邮箱: ">{{ skuInfo.receiveEmail }}</el-descriptions-item>
    </el-descriptions>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="发货卡密" prop="cardKeyStr">
        <div >
          输入格式: 卡号->卡密->pin
          <el-button style="margin-left:16px;" @click="getPreviewCardkeyData" type="primary" size="small" v-if="formData.cardKeyStr">预览</el-button>
        </div>
        <ul >
          <li v-for="(item,index) in formData.cardKeyList" :key="index">
            <el-input
              v-model.trim="item.cardKeyStr"
              :clearable="true"
              :show-word-limit="true"
              placeholder="卡号->密码->pin码"
            />
            <el-button v-if="!index" @click="addCardKeyItem" type="primary">+</el-button>
            <el-button v-else @click="removeCardKeyItem(item, index)" type="info">-</el-button>
          </li>
        </ul>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          :autosize="{ minRows: 3, maxRows: 3 }"
          :clearable="true"
          :show-word-limit="true"
          style="width:100%;"
          placeholder="请输入备注"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <div style="text-align:center;">
      <el-button :loading="formLoading" type="primary" @click="submitForm">
        确定发货
      </el-button>
      <el-button @click="close">返回</el-button>
    </div>
  </Dialog>
  <Dialog v-model="cardKeyDataVisible" title="预览卡密" width="600px">
    <el-table :data="previewCardkeyData" style="width: 100%">
      <el-table-column property="cardNumber" label="卡号" width="280" />
      <el-table-column property="code" label="密码" width="130" />
      <el-table-column property="pin" label="pin码" />
    </el-table>
  </Dialog>
</template>

<script setup >
import {EnumDeliveryMethodType} from "@/config/spu";
import {auditOrder} from '@/api/mall/trade/order';
import {previewCardkey} from "@/api/digital/cardkeyproduct";
defineOptions({ name: 'TradeOrderSendCardKeyForm' })
const emit = defineEmits(['auditSuccess'])
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const cardKeyDataVisible = ref(false) // 弹窗的是否展示
const previewCardkeyData = ref([]);
const formRef = ref();
const formLoading = ref(false);
const formData = ref({
  cardKeyStr: "null->null->null",
  remark: "",
  cardKeyList: [{
    cardKeyStr: "null->null->null"
  }]
});

// 监听formData.value.cardKeyList变化
watch(() => formData.value.cardKeyList, (newVal, oldVal) => {
  formData.value.cardKeyStr = formData.value.cardKeyList.map(item=> {
    // 去掉空格
    return item.cardKeyStr.replace(/\s*/, "");
  }).join("\n");
}, {
  deep: true
})

const rules = reactive({
  cardKeyStr: [required],
});

const props = defineProps({
  orderInfo: {
    type: Object,
    default() {
      return null;
    }
  }
});

const skuInfo = computed(()=> {
  if(props.orderInfo) {
    return props.orderInfo.items[0];
  }

  return {};
});

const open = () => {
  formData.value.remark = "";
  formData.value.cardKeyStr = "null->null->null";
  formData.value.cardKeyList =[{
    cardKeyStr: "null->null->null"
  }];
  formLoading.value = false;
  dialogVisible.value = true
}

function addCardKeyItem() {
  formData.value.cardKeyList.push({
    cardKeyStr: "null->null->null"
  });
}

function removeCardKeyItem(item, index) {
  formData.value.cardKeyList.splice(index, 1);
}

const getPreviewCardkeyData = async ()=> {
  let result = await checkCardKeyValid().catch(e=> {
    message.warning(e);
  });
  if(!result) {
    return;
  }

  previewCardkey({
    secret: formData.value.cardKeyStr
  }).then((data)=> {
    cardKeyDataVisible.value = true;
    previewCardkeyData.value = data;
  }).catch(e=> {
  });
}

function checkCardKeyValid() {
  return new Promise((resolve, reject)=> {
    for(let i=0; i<formData.value.cardKeyList.length; i++) {
      let {cardKeyStr} = formData.value.cardKeyList[i];
      if(!cardKeyStr) {
        reject("请输入完整后提交");
        break;
      }

      cardKeyStr = cardKeyStr.replace(/\s*/g, "");
      if(cardKeyStr.split("->").length != 3) {
        reject("每条数据必须有两个->");
        break;
      }
      if(cardKeyStr.split("null").length == 4) {
        reject("每条数不能有三个null");
        break;
      }

      resolve(true);
    }
  });
}

const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
  } catch (e) {
    formLoading.value = false;
    message.error('必填字段项不完整，请输入后提交')
    throw e // 目的截断之后的校验
  }
}

const close = ()=> {
  formLoading.value = false;
  dialogVisible.value = false;
}

const submitForm = async ()=> {
  formLoading.value = true

  // 校验表单数据
  await validate();
  let result = await checkCardKeyValid().catch(e=> {
    message.warning(e);
  });
  if(!result) {
    formLoading.value = false
    return;
  }
  let cardKeyStr = formData.value.cardKeyStr;

  auditOrder({
    id: props.orderInfo.id,
    cardSecret: cardKeyStr,
    remark: formData.value.remark
  }).then(()=> {
    message.success("审核成功");
    dialogVisible.value = false;
    emit("auditSuccess");
    formLoading.value = false;
  }).catch(e=> {
    formLoading.value = false;
  });
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.order-send-card-key-form-dialog {
  ul {
    list-style: none;
    padding: 0;
    margin: 0px;
    width: 100%;
    margin-top: 16px;
    li {
      margin-bottom: 12px;
      .el-input {
        width: 200px;
        margin-right: 8px;
      }
      &:last-of-type {
        margin-bottom: 0px;
      }
    }
  }
}
</style>
